package cn.fetosoft.woodpecker.core.jmeter.element.controller;

import cn.fetosoft.woodpecker.core.data.entity.BaseElement;
import cn.fetosoft.woodpecker.core.data.entity.element.controller.ModuleControllerElement;
import cn.fetosoft.woodpecker.core.data.form.ElementForm;
import cn.fetosoft.woodpecker.core.data.service.ElementService;
import cn.fetosoft.woodpecker.core.jmeter.element.AbstractElementBuild;
import cn.fetosoft.woodpecker.core.jmeter.extension.ModuleControllerExt;
import lombok.extern.slf4j.Slf4j;
import org.apache.jmeter.testelement.TestElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 创建模块控制器
 * @author guobingbing
 * @version 1.0
 * @wechat t_gbinb
 * @create 2021/7/27 9:51
 */
@Slf4j
@Component("moduleControllerImpl")
public class CreateModuleControllerImpl extends AbstractElementBuild {

	@Autowired
	private ElementService elementService;

	@Override
	protected TestElement convert(BaseElement be) throws Exception {
		ModuleControllerElement element = (ModuleControllerElement) be;
		ModuleControllerExt controller = new ModuleControllerExt();
		List<BaseElement> elementList = this.findElements(element.getPlanId());
		String[] arr = element.getFragments().split(",");
		List<BaseElement> children = new ArrayList<>();
		for(String fm : arr){
			List<BaseElement> fragmentChild = this.findElements(elementList, fm);
			if(!CollectionUtils.isEmpty(fragmentChild)){
				children.addAll(fragmentChild);
			}
		}
		controller.setChildren(children);
		return controller;
	}

	private List<BaseElement> findElements(String planId) throws Exception{
		ElementForm form = new ElementForm();
		form.setPlanId(planId);
		form.setRows(0);
		form.setAscField("createTime");
		return elementService.selectListByForm(form, BaseElement.class);
	}

	/**
	 * 过滤子元素
	 * @param elements 所有元素
	 * @param parentId 父ID
	 * @return
	 */
	private List<BaseElement> findElements(List<BaseElement> elements, String parentId){
		return elements.stream().filter(e -> e.getParentId().equals(parentId))
				.sorted(Comparator.comparingInt(BaseElement::getSort))
				.collect(Collectors.toList());
	}
}
